<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" :disabled="!checkPermission('yuangong1')" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" :disabled="!checkPermission('yuangong2')" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="ShowAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delExcel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="page.size" :total="page.total" @current-change="currentChange" />
        </el-row>
      </el-card>
      <add-Demployee :show-dialog.sync="showDialog" />
      <el-dialog title="头像二维码" :visible="isShowAvatar" @close="cancel">
        <el-row type="flex" justify="center">
          <canvas ref="myAvatar" />
        </el-row>
      </el-dialog>
      <!--  -->
      <assignRole ref="assignRole" :is-show-role.sync="showAssignRole" :user-id="userId" />
    </div>
  </div>
</template>

<script>
// 引入api员工详情请求 删除
import { getEmployee, delEmployee } from '@/api/employees'
// 引入枚举数据
import employeeEnum from '@/api/constant/employees'
// 引入导出js
import { export_json_to_excel } from '@/vendor'
// 引入过滤器
import { formatDate } from '@/filters'
// 引入新增input弹窗组件
import addDemployee from './components/add-employee.vue'
// 引入二维码生成
import QRCode from 'qrcode'
// 引入角色弹窗
import assignRole from './components/assign-role.vue'
export default {
  components: { addDemployee, assignRole },
  // 过滤器(时间切割)
  // filters: {
  //   formatDate(old) {
  //     return old.split('T')[0]
  //   }
  // },
  data() {
    return {
      // 弹窗二维码
      isShowAvatar: false,
      // 角色详情
      employeeList: [],
      page: {
        page: 1, // 页码
        size: 5, // 页码条
        total: 0 // 页码总条
      },
      showDialog: false,
      // 角色弹窗
      showAssignRole: false,
      userId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    // 删除员工
    async delExcel(id) {
      // 询问
      await this.$confirm('确认要删除吗？')
      // 请求
      await delEmployee(id)
      // 判断 如果最后一页只有一条数据 删完显示前页
      if (this.employeeList.length === 1 && this.page.page > 1) {
        this.page.page -= 1
      }
      // 提示
      this.$message.success('删除成功')
      // 更新
      this.getEmployee()
    },
    // 导出
    async exportExcel() {
      // 获取所有员工详情列表
      const { rows } = await getEmployee({ page: 1, size: this.page.total })
      // console.log(rows)
      // 导出表头需要格式
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      // 遍历 交给turnArray函数处理
      const data = rows.map(userObj => {
        return this.turnArray(userObj, header)
      })
      console.log(rows)
      console.log(data)
      // 导出函数 放入对象值
      export_json_to_excel({
        header,
        data
      })
    },
    // 匹配
    turnArray(userObj, headers) {
      const userArr = []
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      headers.forEach(key => {
        // dict 中的 对象中的key
        const enkey = dict['key']
        let value = userObj[enkey]
        // 枚举数据 转换数据对应 判断聘用形式
        if (enkey === 'formOfEmployment') {
          const obj = employeeEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        // 判断 转换数据对应入职转正时间
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          // 格式化日期
          value = formatDate(value)
        }
        userArr.push(value)
      })
      return userArr
    },
    // 角色详情请求
    async getEmployee() {
      const { rows, total } = await getEmployee(this.page)
      this.employeeList = rows.map(user => {
        return {
          // 原数组
          ...user,
          // 短路运算 本地没有就走1  线上右就走enableState
          enableState: user.enableState || 1
        }
      })
      this.page.total = total
    },
    // 分页点击显示相应
    currentChange(newPage) {
      // 当前页
      this.page.page = newPage
      // 更新
      this.getEmployee()
    },
    // 判断显示聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要拿值的时候, 只需要, 查找当前的数组中 id === cell 那个对象
      // 输出 value 即可
      const obj = employeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 二维码弹窗
    ShowAvatar(url) {
      if (url) {
        this.isShowAvatar = true

        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myAvatar, url)
        })
      }
    },
    cancel() {
      this.isShowAvatar = false
    },
    // 弹窗角色
    async showRole(id) {
      this.showAssignRole = true
      // 传id
      this.userId = id
      // 获取点击id
      await this.$refs.assignRole.getCheckedRole(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 140px;
  object-fit: cover;
}
</style>
